package com.huixi.microspur.sysadmin.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huixi.microspur.commons.enums.EnableFlagEnum;
import com.huixi.microspur.commons.page.PageData;
import com.huixi.microspur.commons.page.PageFactory;
import com.huixi.microspur.commons.page.PageQuery;
import com.huixi.microspur.sysadmin.mapper.WjUserMapper;
import com.huixi.microspur.sysadmin.pojo.entity.appeal.WjAppeal;
import com.huixi.microspur.sysadmin.pojo.entity.appeal.WjAppealEndorse;
import com.huixi.microspur.sysadmin.pojo.entity.dynamic.WjDynamic;
import com.huixi.microspur.sysadmin.pojo.entity.user.WjUser;
import com.huixi.microspur.sysadmin.pojo.entity.user.WjUserWx;
import com.huixi.microspur.sysadmin.pojo.vo.user.UserDataVO;
import com.huixi.microspur.sysadmin.pojo.vo.user.UserPageVo;
import com.huixi.microspur.sysadmin.service.*;
import com.huixi.microspur.sysadmin.util.CommonUtil;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author xzl
 * @since 2020-01-17
 */
@Service
public class WjUserServiceImpl extends ServiceImpl<WjUserMapper, WjUser> implements WjUserService {

    @Resource
    private WjUserService wjUserService;

    @Resource
    private WjAppealService wjAppealService;

    @Resource
    private WjDynamicService wjDynamicService;

    @Resource
    private WjAppealEndorseService wjAppealEndorseService;

    @Resource
    private WjUserWxService wjUserWxService;

    @Resource
    private WxMaService wxMaService;

    /**
     * 获取session_key
     *
     * @param code 用户code
     * @return java.lang.String
     * @Author 李辉
     * @Date 2019/11/23 4:31
     **/
    @SneakyThrows
    @Override
    public WxMaJscode2SessionResult getWxSession(String code) {
        return wxMaService.getUserService().getSessionInfo(code);
    }


    /**
     * 获取用户加密信息 并且保存
     *
     * @param
     * @return void
     * @Author 李辉
     * @Date 2019/11/23 4:33
     **/
    @Override
    public WxMaUserInfo getEncryptionUserInfo(String encryptedData, String session_key, String ivKey) {
        // 返回加密的数据
        return wxMaService.getUserService().getUserInfo(session_key, encryptedData, ivKey);
    }

    /**
     * 根据用户code 获取用户的 openId 和 sessionKey , 来确定有没有授权过。 如果授权发放用户信息 ，没有就创建一个用户
     *
     * @param code 用户小程序的code
     * @return WjUser 用户信息
     * @Author 叶秋
     * @Date 2020/2/1 20:17
     **/
    @Override
    public WjUser detectionUserAuthorization(String code) {
        WxMaJscode2SessionResult wxSessionKey = getWxSession(code);

        // 根据open_id 检测数据库中是否有此用户
        QueryWrapper<WjUserWx> wjUserWxQueryWrapper = new QueryWrapper<>();
        wjUserWxQueryWrapper.eq("wx_open_id", wxSessionKey.getOpenid());
        WjUserWx wjUserWx = wjUserWxService.getOne(wjUserWxQueryWrapper);

        if (ObjectUtil.isNotNull(wjUserWx)) {
            return wjUserService.getById(wjUserWx.getUserId());
        }

        // 检测用户不存在的情况 随机创建用户资料
        WjUser wjUser = CommonUtil.randomCreateUserInfo();
        WjUserWx newWjUserWx = new WjUserWx().setUserId(wjUser.getUserId())
                .setWxOpenId(wxSessionKey.getOpenid());

        boolean save = wjUserService.save(wjUser);
        boolean save1 = wjUserWxService.save(newWjUserWx);

        return wjUser;

    }

    /**
     * 根据用户id 查询用户信息 包括需要查询其他表的一些数据（诉求、动态...）
     *
     * @param userId
     * @return com.huixi.microspur.commons.util.wrapper.Wrapper
     * @Author 叶秋
     * @Date 2020/6/1 21:55
     **/
    @Override
    public UserDataVO getByIdUserData(String userId) {
        WjUser byId = wjUserService.getById(userId);
        UserDataVO userDataVO = new UserDataVO();
        BeanUtil.copyProperties(byId, userDataVO);

        // 查询诉求 数量
        int appealCount = getAppealCount(userId);
        userDataVO.setAppealCount(appealCount);

        // 查询动态 数量
        int dynamicCount = getDynamicCount(userId);
        userDataVO.setDynamicCount(dynamicCount);

        // 被点赞数
        int endorseCount = getEndorseCount(userId);
        userDataVO.setEndorseCount(endorseCount);

        return userDataVO;
    }

    @Override
    public void banUser(String userId) {
        WjUser user = getById(userId);
        if (user != null) {
            user.setEnableFlag(EnableFlagEnum.FORBIDDEN.value());
            updateById(user);
        }
    }

    /**
     *  分页查询用户
     * @param pageQuery 分页条件
     */
    @Override
    public PageData<UserPageVo> page(PageQuery pageQuery) {
        Page<WjUser> page = PageFactory.createPage(pageQuery);
        page(page);

        List<WjUser> records = page.getRecords();
        List<UserPageVo> pageVos = records.stream()
                .map(this::entity2UserPageVo).collect(Collectors.toList());

        PageData<UserPageVo> pageData = new PageData<>();
        pageData.setRecords(pageVos);
        pageData.setCurrent((int) page.getCurrent());
        pageData.setSize((int) page.getSize());
        pageData.setTotal((int) page.getTotal());
        return pageData;
    }

    /**
     *  entity 转 userPageVo
     */
    private UserPageVo entity2UserPageVo(WjUser entity) {
        if (entity == null) {
            return null;
        }
        UserPageVo vo = UserPageVo.builder()
                .userId(entity.getUserId())
                .nickName(entity.getNickName())
                .realName(entity.getRealName())
                .headPortrait(entity.getHeadPortrait())
                .sex(entity.getSex())
                .mobile(entity.getMobile())
                .company(entity.getCompany())
                .email(entity.getEmail())
                .signature(entity.getSignature())
                .introduce(entity.getIntroduce())
                .address(entity.getAddress())
                .identityCard(entity.getIdentityCard())
                .createTime(entity.getCreateTime())
                .updateTime(entity.getUpdateTime())
                .enableFlag(entity.getEnableFlag()).build();

        if (StringUtils.isNotBlank(entity.getUserId())) {
            // 动态数量
            int dynamicCount = getDynamicCount(entity.getUserId());
            // 被点赞数
            int endorseCount = getEndorseCount(entity.getUserId());
            // 诉求数量
            int appealCount = getAppealCount(entity.getUserId());
            vo.setDynamicCount(dynamicCount);
            vo.setEndorseCount(endorseCount);
            vo.setAppealCount(appealCount);
        }
        return vo;
    }

    /**
     *   根据id查询动态数量
     * @param userId id
     */
    private int getDynamicCount(String userId) {
        QueryWrapper<WjDynamic> wjDynamicQueryWrapper = new QueryWrapper<>();
        wjDynamicQueryWrapper.eq("user_id", userId);
        return wjDynamicService.count(wjDynamicQueryWrapper);
    }

    /**
     *  根据id查询被点赞数量
     * @param userId id
     */
    private int getEndorseCount(String userId) {
        QueryWrapper<WjAppealEndorse> wjAppealEndorseQueryWrapper = new QueryWrapper<>();
        wjAppealEndorseQueryWrapper.eq("user_id", userId);
        return wjAppealEndorseService.count(wjAppealEndorseQueryWrapper);
    }

    /**
     *  根据id查询诉求数量
     * @param userId id
     */
    private int getAppealCount(String userId) {
        QueryWrapper<WjAppeal> wjAppealQueryWrapper = new QueryWrapper<>();
        wjAppealQueryWrapper.eq("user_id", userId);
        return wjAppealService.count(wjAppealQueryWrapper);
    }
}
